package com.jason.www.jdk8;


import com.jason.www.jdk8.pojo.Person;
import org.junit.Test;

import java.util.Comparator;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 方法引用:若Lambda 体中的内容有方法已经实现了,我们可以使用"方法引用"
 */
public class C_MethodRef {
    @Test
    public void test1(){
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("shuai");

        //方法引用,对象::实例方法名
        Consumer<String> consumer = System.out::println;
        consumer.accept("test");
    }

    @Test
    public void test2(){
        Person person = new Person();
        Supplier<String> supplier = () -> person.getName();
        String str = supplier.get();
        System.err.println(str);

        //方法引用,对象::实例方法名
        Supplier<Integer> sup = person::getAge;
        Integer age = sup.get();
        System.out.println(age);
    }

    //类::静态方法名
    @Test
    public void test3(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        System.out.println(com.compare(1,2));
        //使用前提,compare的参数和返回值与Comparator一致
        Comparator<Integer> comparator = Integer :: compare;
        System.out.println(comparator.compare(1,2));
    }

    //类::实例方法名
    @Test
    public void test4(){
        BiPredicate<String, String> bp = (x, y) -> x.equals(y);
        //使用条件:第一个参数是实例方法调用者,第二个参数是实例方法的参数
        BiPredicate<String, String> biPredicate = String :: equals;
    }

    //构造器引用
    @Test
    public void test5(){
        Supplier<Person> sup = () -> new Person();

        //构造器引用方式
        Supplier<Person> supplier = Person :: new;
        Person person = supplier.get();
        System.out.println(person);
    }

    //构造器引用
    @Test
    public void test6(){
        Function<Integer, Person> fun = (x) -> new Person(x);

        Function<Integer, Person> function = Person :: new;
        Person person = function.apply(2);
        System.out.println(person);
        System.out.println("--------------------");

        BiFunction<String, Integer, Person> biFunction = Person :: new;
        Person person2 = biFunction.apply("张三", 23);
        System.out.println(person2);
    }

    //数组引用
    @Test
    public void test7(){
        Function<Integer, String[]> fun = (x) -> new String[x];
        String[] strs = fun.apply(8);
        System.out.println(strs.length);

        Function<Integer, String[]> function = String[] :: new;
        String[] strArray = function.apply(6);
        System.out.println(strArray.length);
    }
}
